package com.hboxs.asl.controller.app;

import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.entity.VerificationCode;
import com.hboxs.asl.service.MemberService;
import com.hboxs.asl.service.VerificationCodeService;
import com.hboxs.asl.util.PhonePatternUtils;
import com.hboxs.asl.util.sms.ChuangLanSms;
import com.hboxs.asl.util.sms.YunPianSms;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Random;

/**
 * Controller -- 手机验证码
 */
@Controller("appPhoneController")
@RequestMapping("/app/phone")
public class PhoneController extends BaseController {

    /**
     * 注册验证码内容
     */
    private static final String content = "【易经应用】您的验证码是%s";// 短信内容
    /**
     * 找回密码短信内容
     */
    private static final String validatecontent = "【易经应用】您的找回密码验证码是%s";// 短信内容
    /**
     * 有效期
     */
    private static final Long availableTime = 30 * 60 * 1000l;
    /**
     * 短信发送间隔
     */
    private static final Long sendInterval = 1 * 60 * 1000l;

    @Resource(name = "verificationCodeServiceImpl")
    private VerificationCodeService verificationCodeService;
    @Resource(name = "memberServiceImpl")
    private MemberService memberService;

    /**
     * 发送验证码
     *
     * @param phone
     * @return
     * @throws HttpException
     * @throws IOException
     */
    @RequestMapping(value = "/sendCode", method = RequestMethod.POST)
    @ResponseBody
    protected Object sendCode(String phone) throws HttpException, IOException {
        try {
            if (StringUtils.isEmpty(phone)) {
                return JsonMessage.error("对不起，手机不能为空");
            }

            if (!PhonePatternUtils.isChinaPhoneLegal(phone)) {
                return JsonMessage.error("手机号码无效");
            }

            if (memberService.usernameExists(phone)) {
                return JsonMessage.error("该手机号已经注册");
            }

            Date date = new Date();
            VerificationCode verificationCode = verificationCodeService.findByPhone(phone);

            // 判断发送间隔是否正常
            if (verificationCode != null && (date.getTime() - verificationCode.getSendDate().getTime()) < sendInterval) {
                return JsonMessage.error("验证码已经发送，请稍后重试");
            }

            StringBuilder code = new StringBuilder();

            // 判断验证码是否过期
            if (verificationCode != null && (date.getTime() - verificationCode.getSendDate().getTime()) < availableTime) {
                // 未过期， 直接使用旧验证码
                code.append(verificationCode.getCode());
            } else {
                //创建验证码
                Random random = new Random();
                for (int i = 0; i < 6; i++) {
                    code.append(String.valueOf(random.nextInt(10)));
                }

                if (verificationCode == null) {
                    //当用户手机号码不存在记录时，创建对象并保存到数据表中
                    verificationCode = new VerificationCode();
                    verificationCode.setPhone(phone);
                    verificationCode.setCode(code.toString());
                    verificationCode.setSendDate(new Date());
                    verificationCodeService.save(verificationCode);
                } else {
                    //当存在记录，更新数据
                    verificationCode.setCode(code.toString());
                    verificationCode.setSendDate(date);
                    verificationCodeService.update(verificationCode);
                }
            }

            // 这些号码仅仅打印到控制台，不触发短信发送接口
            if (phone.equals("10086") || phone.equals("13800138000")) {
                logger.info("code:" + code);
                return JsonMessage.success("验证码发送成功");
            }
            logger.info("code:" + code);
            // 设置短信内容
            String smsText = String.format(content, code);

            JSONObject result = YunPianSms.sendSms(phone, smsText);
            logger.info("短信发送结果:" + result.get("msg"));

            return JsonMessage.success("验证码发送成功");

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }


    /**
     * 发送短信验证码
     *
     * @param phone
     * @return
     * @throws HttpException
     * @throws IOException
     */
    @RequestMapping(value = "/find_code", method = RequestMethod.POST)
    @ResponseBody
    protected Object find_code(String phone) throws HttpException, IOException {
        try {
            if (StringUtils.isEmpty(phone)) {
                return JsonMessage.error("对不起，手机不能为空");
            }
            if (!PhonePatternUtils.isChinaPhoneLegal(phone)) {
                return JsonMessage.error("手机号码无效");
            }

            Date date = new Date();
            VerificationCode verificationCode = verificationCodeService.findByPhone(phone);

            // 判断发送间隔是否正常
            if (verificationCode != null && (date.getTime() - verificationCode.getSendDate().getTime()) < sendInterval) {
                return JsonMessage.error("验证码已经发送，请稍后重试");
            }

            StringBuilder code = new StringBuilder();

            // 判断验证码是否过期
            if (verificationCode != null && (date.getTime() - verificationCode.getSendDate().getTime()) < availableTime) {
                // 未过期， 直接使用旧验证码
                code.append(verificationCode.getCode());
            } else {
                //创建验证码
                Random random = new Random();
                for (int i = 0; i < 6; i++) {
                    code.append(String.valueOf(random.nextInt(10)));
                }

                if (verificationCode == null) {
                    //当用户手机号码不存在记录时，创建对象并保存到数据表中
                    verificationCode = new VerificationCode();
                    verificationCode.setPhone(phone);
                    verificationCode.setCode(code.toString());
                    verificationCode.setSendDate(new Date());
                    verificationCodeService.save(verificationCode);
                } else {
                    //当存在记录，更新数据
                    verificationCode.setCode(code.toString());
                    verificationCode.setSendDate(date);
                    verificationCodeService.update(verificationCode);
                }
            }

            // 这些号码仅仅打印到控制台，不触发短信发送接口
            if (phone.equals("10086") || phone.equals("13800138000")) {
                logger.info("code:" + code);
                return JsonMessage.success("验证码发送成功");
            }
            logger.info("code:" + code);
            // 设置短信内容
            String smsText = String.format(content, code);
            JSONObject result = YunPianSms.sendSms(phone, smsText);
            logger.info("短信发送结果:" + result.get("msg"));

            return JsonMessage.success("验证码发送成功");

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 发送短信找回密码
     *
     * @param phone
     * @return
     * @throws HttpException
     * @throws IOException
     */
    @RequestMapping(value = "/findCode", method = RequestMethod.POST)
    @ResponseBody
    protected Object findCode(String phone) throws HttpException, IOException {
        try {
            if (StringUtils.isEmpty(phone)) {
                return JsonMessage.error("对不起，手机不能为空");
            }

            if (!PhonePatternUtils.isChinaPhoneLegal(phone)) {
                return JsonMessage.error("手机号码无效");
            }

            if (!memberService.usernameExists(phone)) {
                return JsonMessage.error("该手机号不存在");
            }

            Date date = new Date();
            VerificationCode verificationCode = verificationCodeService.findByPhone(phone);

            // 判断发送间隔是否正常
            if (verificationCode != null && (date.getTime() - verificationCode.getSendDate().getTime()) < sendInterval) {
                return JsonMessage.error("验证码已经发送，请稍后重试");
            }

            StringBuilder code = new StringBuilder();

            // 判断验证码是否过期
            if (verificationCode != null && (date.getTime() - verificationCode.getSendDate().getTime()) < availableTime) {
                // 未过期， 直接使用旧验证码
                code.append(verificationCode.getCode());
            } else {
                //创建验证码
                Random random = new Random();
                for (int i = 0; i < 6; i++) {
                    code.append(String.valueOf(random.nextInt(10)));
                }

                if (verificationCode == null) {
                    //当用户手机号码不存在记录时，创建对象并保存到数据表中
                    verificationCode = new VerificationCode();
                    verificationCode.setPhone(phone);
                    verificationCode.setCode(code.toString());
                    verificationCode.setSendDate(new Date());
                    verificationCodeService.save(verificationCode);
                } else {
                    //当存在记录，更新数据
                    verificationCode.setCode(code.toString());
                    verificationCode.setSendDate(date);
                    verificationCodeService.update(verificationCode);
                }
            }

            // 这些号码仅仅打印到控制台，不触发短信发送接口
            if (phone.equals("10086") || phone.equals("13800138000")) {
                logger.info("code:" + code);
                return JsonMessage.success("验证码发送成功");
            }
            logger.info("code:" + code);
            // 设置短信内容
            String smsText = String.format(content, code);
            JSONObject result = YunPianSms.sendSms(phone, smsText);
            logger.info("短信发送结果:" + result.get("msg"));

            return JsonMessage.success("验证码发送成功");

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }
}
